//
//  AQRSlidesView.m
//  IfengNews
//
//  Created by Ryan on 13-5-13.
//
//

#import "AQRSlidesView.h"
#import "AQRSlideViewController.h"
#import "AQRImageZoomView.h"
@interface AQRSlidesView ()
@property (nonatomic,strong) NSArray *children;
@property (nonatomic,strong) UIView *markView;

@end

@implementation AQRSlidesView
//@synthesize currentIndex;


- (id)init{
    self = [super init];
    if(self){
        NSAssert(false, @"用initWithFrame那个");
    }
    return self;
}

- (int )preIndex{
  
    return [self scrollIndex2Index:_scrollIndex-1];
}

- (int )nextIndex{

    return [self scrollIndex2Index:_scrollIndex+1];
}

- (int )currentIndex{
    return [self scrollIndex2Index:_scrollIndex];
    
}

- (int)scrollIndex2Index:(int)aindex{
    if(self.count == 0)
        return 0;
    
    if(aindex>=0){
        return aindex%self.count;
    }else{
        return  self.count+ (aindex%self.count);
    }
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate=self;
        self.pagingEnabled=YES;
        self.userInteractionEnabled=YES;
        self.showsHorizontalScrollIndicator=NO;
        self.showsVerticalScrollIndicator=NO;
        self.markView=[[UIView alloc] init];
        
        UIPanGestureRecognizer *recognizer=[[UIPanGestureRecognizer alloc] init];
        [self.markView addGestureRecognizer:recognizer];
        
        [self.markView setBackgroundColor:[UIColor clearColor]];
        self.markView.hidden=YES;
        self.isCycle=NO;
        self.floatPre=0;
        
//    self.contentInset=UIEdgeInsetsMake(20, 0, 0, 0);
//        self.bounces=NO;

    }
    return self;
}

- (void)dealloc{
    [self.markView removeFromSuperview];
}

- (void)willMoveToWindow:(UIWindow *)newWindow{
    if(!self.children){
        
        if(self.superview){
            self.markView.frame=self.frame;
            [self.superview addSubview:self.markView];
        }
        NSMutableArray *array=[NSMutableArray array];
        for(int i=0;i<3;i++){
            AQRSlideViewController *child=[[[_datasource childrenClass] alloc] init];
            
                  
            //child.view.contentInset=UIEdgeInsetsMake(20, 0, 0, 0);
           
            [child slideDidCreate:self param:[_datasource childrenCreateParams]];
        
            [array addObject:child];
        }
        self.children=array;
        [self loadData];
    }    
}


- (void)initView{
      
    
    
}

- (void)reloadData{
    _scrollIndex=[_datasource initIndex];
  
    CGRect arect=self.frame;
    self.count=[_datasource photoCount];
    
    if(self.isCycle){
        _scrollIndex+=self.count;
        self.contentSize=CGSizeMake([_datasource photoCount]*arect.size.width*3, arect.size.height);
        self.floatPre=[_datasource photoCount]*arect.size.width;
    }else{
        self.contentSize=CGSizeMake([_datasource photoCount]*arect.size.width, arect.size.height);
    }
    
    
    [self setContentOffset:CGPointMake(arect.size.width*_scrollIndex, 0)];
    [self frameBody:4];
    //[self setContentOffset:CGPointMake(arect.size.width*[_datasource currentSliderBehind], 0)];
}

- (void)loadNextData {
    [self didChangeBody:[self scrollIndex]+1];
    //[self reloadData];
}

- (void)loadData{
    _scrollIndex=[_datasource initIndex];
    CGRect arect=self.frame;
    self.count=[_datasource photoCount];
    if(self.isCycle){
        _scrollIndex+=self.count;
        self.contentSize=CGSizeMake([_datasource photoCount]*arect.size.width*3, arect.size.height);
        self.floatPre=[_datasource photoCount]*arect.size.width;
        
    }else{
        self.contentSize=CGSizeMake([_datasource photoCount]*arect.size.width, arect.size.height);
    }
    
    
   
    [self setContentOffset:CGPointMake(arect.size.width*_scrollIndex, 0)];
    [self frameBody:0];
}




- (void)initBodyIndex{
    preBody=2;
    currentBody=0;
    nextBody=1;
}

- (void)initFrame{
    AQRSlideViewController *current = [self.children objectAtIndex:currentBody];
    CGRect rect = self.frame;
    [self updateFrameWithViewController:current WithFrame:rect];
    
     [current.view setCenter:CGPointMake((rect.size.width/2.0f)+(rect.size.width*_scrollIndex), rect.size.height/2.0f)];
    
    [current slideChange:self frame:current.view.frame statue:statueAQRSlideCurrent];
    [self addSubview:current.view];
    [self addSubview:[self framePre:_scrollIndex].view];
    [self addSubview:[self frameNext:_scrollIndex].view];
    
    
}

- (AQRSlideViewController *)framePre:(int)_currentIndex{
    int preIndex;
        preIndex=_scrollIndex-1<0?-1:_scrollIndex-1;
   
    
    
    AQRSlideViewController *pre =[self.children objectAtIndex:preBody];
    CGRect rect = self.frame;
    [self updateFrameWithViewController:pre WithFrame:rect];
    
    if(preIndex==-1){
      
        [pre.view setCenter:CGPointMake(-rect.size.width/2.0f, rect.size.height/2.0f)];
    }else{
        [pre.view setCenter:CGPointMake(rect.size.width*_scrollIndex-rect.size.width/2.0f, rect.size.height/2.0f)];
    }
    [pre slideChange:self frame:pre.view.frame statue:statueAQRSlidePre];
    return pre;
}


- (AQRSlideViewController *)currentController{
    return [self.children objectAtIndex:currentBody];
}

- (AQRSlideViewController *)frameNext:(int)_currentIndex{
    int nextIndex;
    if(self.isCycle){
        nextIndex=_scrollIndex+1;
    }else{
        nextIndex=_scrollIndex+1>=[self.datasource photoCount]?-1:_scrollIndex+1;
    }
    
   
    
    
    
    AQRSlideViewController *next=[self.children objectAtIndex:nextBody];
    CGRect rect = self.frame;
    [self updateFrameWithViewController:next WithFrame:rect];
    if(nextIndex==-1){
        
        [next.view setCenter:CGPointMake(-rect.size.width/2.0f, rect.size.height/2.0f)];
    }else{
        [next.view setCenter:CGPointMake(rect.size.width*nextIndex+rect.size.width/2.0f, rect.size.height/2.0f)];
    }
    [next slideChange:self frame:next.view.frame statue:statueAQRSlideNext];
    return next;
}

- (void)frameBody:(int)flag{
   
    if(flag==0){
        [self initBodyIndex];
        [self initFrame];
        self.curretnDirection=directionAQRSlidesView_none;
    }else if (flag==1){
        [self frameNext:_scrollIndex];
        self.curretnDirection=directionAQRSlidesView_right;
    }else if (flag==2){
        [self framePre:_scrollIndex];
         self.curretnDirection=directionAQRSlidesView_left;
    }else if(flag==4){
        [self initFrame];
        self.curretnDirection=directionAQRSlidesView_none;
    }
    [self didChangeStatue];
}

- (AQRSlideViewController *)currentChild{
    return [self.children objectAtIndex:currentBody];
}

- (void)didChangeStatue{
    AQRSlideViewController *body=[self.children objectAtIndex:currentBody];
    [body slideChange:self statue:statueAQRSlideCurrent];
    body=[self.children objectAtIndex:preBody];
    [body slideChange:self statue:statueAQRSlidePre];
    body=[self.children objectAtIndex:nextBody];
    [body slideChange:self statue:statueAQRSlideNext];
}


- (int)checkCycle{
    int contentOffsetX = self.contentOffset.x;
    if(contentOffsetX == (self.contentSize.width-self.bounds.size.width)) {
     [self setContentOffset:CGPointMake(self.bounds.size.width*self.count*2-self.bounds.size.width, 0) animated:NO];
        for(AQRSlideViewController *ctrl in self.children){
            CGRect frame=ctrl.view.frame;
            frame.origin.x-=self.bounds.size.width*(self.count);
            ctrl.view.frame=frame;
        }
        _scrollIndex=2*self.count-2;
        
        return -self.count;
    }else
    if(contentOffsetX == 0) {
        [self setContentOffset:CGPointMake(self.bounds.size.width*(self.count), 0) animated:NO];
        _scrollIndex=self.count+1;
     
        for(AQRSlideViewController *ctrl in self.children){
            CGRect frame=ctrl.view.frame;
            frame.origin.x+=self.bounds.size.width*(self.count);
            ctrl.view.frame=frame;
        }
      
        
        return self.count;
        
    }
    return 0;
}

- (void)didChangeBody:(int)_index{
    
    @synchronized(self){
      
        if(_isCycle){
            _index+=[self checkCycle];
                
               
            
        }
        
        if(_index>_scrollIndex){
            _scrollIndex=_index;
            int n=preBody;
            preBody=currentBody;
            currentBody=nextBody;
            nextBody=n;
            
            [self frameBody:1];
        }else if(_index<_scrollIndex){
            _scrollIndex=_index;
            int n=nextBody;
            nextBody=currentBody;
            currentBody=preBody;
            preBody=n;
           
            [self frameBody:2];
        }else{
            _scrollIndex=_index;
            self.curretnDirection=directionAQRSlidesView_none;
        }
        self.markView.hidden=YES;
        self.scrollEnabled=YES;
        //self.panGestureRecognizer.delegate
        
    }
}





- (void)setOffset:(CGPoint )point{
    [UIView animateWithDuration:0.35 animations:^{
        [self setContentOffset:point];
    } completion:^(BOOL finished) {
        [self didChangeBody:[self scrollIndex]];
    }];
}

- (int)scrollIndex{
   // float mid=(self.contentOffset.x-self.floatPre)/self.bounds.size.width;
//    if(mid>=0){
//        return ((int)(mid/self.bounds.size.width))%self.count;
//    }else{
//      return  self.count+ ((int)(mid/self.bounds.size.width))%self.count;
//    }
    
    return (int)(self.contentOffset.x/self.bounds.size.width);
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //通用组件。不要往里面写业务逻辑。。想别的办法
//  [[BlockerView shareInstance] stopShowBlockView];
//  [[NSNotificationCenter defaultCenter] postNotificationName:@"hiddenPicMoreView" object:nil];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)ascrollView willDecelerate:(BOOL)decelerate{
    self.scrollEnabled=NO;
    self.markView.hidden=NO;
    if(!decelerate){
        [self didChangeBody:[self scrollIndex]];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)ascrollView{
    self.scrollEnabled=NO;
    [self didChangeBody:[self scrollIndex]];
}

- (void)updateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    CGRect arect = self.frame;
    
    if(self.isCycle){
        self.contentSize=CGSizeMake([_datasource photoCount]*arect.size.width*3, arect.size.height);
        self.floatPre=[_datasource photoCount]*arect.size.width;
    }else{
        self.contentSize=CGSizeMake([_datasource photoCount]*arect.size.width, arect.size.height);
    }
    
    [self setContentOffset:CGPointMake(arect.size.width*_scrollIndex, 0)];
    [self initFrame];
}

- (void)updateFrameWithViewController:(AQRSlideViewController *)viewController WithFrame:(CGRect)rect
{
    viewController.view.frame = rect;
}

@end
